from datetime import datetime

from flask import Blueprint, request, session
from flask_restful import Api, Resource, marshal_with
from flask_restful.reqparse import RequestParser

from utils.render import json_detail_render
from webapp.config import api_utils
from webapp.config.api_utils import oper_log, check_auth
from webapp.dto_mapper import session_page_fields
from webapp.schema import SessionSchema
from webapp.service.session_service import SessionService

session_app = Blueprint('session', __name__, url_prefix='/api/session')
session_api = Api(session_app)

parser = RequestParser()
parser.add_argument('id', location='json', type=int, trim=True, required=True)
parser.add_argument('session', location='json', type=str, trim=True, required=True)
parser.add_argument('begin_date', location='json', type=str, trim=False, required=True)
parser.add_argument('end_date', location='json', type=str, trim=False, required=True)
parser.add_argument('weeksum', location='json', type=str, trim=False, required=True)


@session_api.resource("", "/")
class SessionApi(Resource):

    @oper_log('查询所有学期', request)
    @check_auth('session:list', request)
    @marshal_with(session_page_fields)
    def get(self):
        params = request.args.items(multi=True)
        params_dict = api_utils.build_params(params)
        return SessionService.query_all(**params_dict)

    @oper_log('删除学期', request)
    @check_auth('session:del', request)
    def delete(self):
        ids = request.get_json()
        session_set = set()
        for _id in ids:
            session_set.add(SessionService.find_by_id(id=_id))
        SessionService.delete(session_set=session_set)

    @oper_log('新增学期', request)
    @check_auth('session:add', request)
    def post(self):
        parser_post = parser.copy()
        parser_post.remove_argument('id')
        parser_post.parse_args()
        params = request.get_json()
        schema = SessionSchema()
        curr_session = schema.load(params, unknown="exclude")
        user = session["user"]
        curr_session.create_by = user["username"]
        SessionService.create(curr_session=curr_session)

    @oper_log('修改学期', request)
    @check_auth('session:edit', request)
    def put(self):
        parser_put = parser.copy()
        parser_put.parse_args()
        params = request.get_json()
        schema = SessionSchema()
        curr_session = schema.load(params, unknown="exclude")
        user = session["user"]
        curr_session.update_by = user["username"]
        SessionService.update(curr_session=curr_session)


@session_api.resource("", "/<int:id>")
class SessionWeekNumApi(Resource):
    @oper_log('查询学期的周数', request)
    @check_auth('session:list', request)
    def get(self, id):
        weeksum = SessionService.find_week()
        return json_detail_render(code=0, data=weeksum)
